# IIS权限修复脚本
# 解决添加服务失败的权限问题

Write-Host "=====================================" -ForegroundColor Cyan
Write-Host "  IIS权限修复脚本" -ForegroundColor Cyan
Write-Host "=====================================" -ForegroundColor Cyan
Write-Host ""

# 检查管理员权限
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

if (-not $isAdmin) {
    Write-Host "❌ 请以管理员身份运行此脚本！" -ForegroundColor Red
    Write-Host ""
    Write-Host "解决方法：" -ForegroundColor Yellow
    Write-Host "  1. 右键PowerShell图标" -ForegroundColor White
    Write-Host "  2. 选择'以管理员身份运行'" -ForegroundColor White
    Write-Host "  3. 重新执行此脚本" -ForegroundColor White
    Write-Host ""
    pause
    exit 1
}

$ProjectRoot = $PSScriptRoot
$ServerPath = Join-Path $ProjectRoot "server"
$ConfigPath = Join-Path $ServerPath "config"
$SiteName = "ScadaServiceManage"
$PoolName = "ScadaServiceManagePool"

Write-Host "项目根目录: $ProjectRoot" -ForegroundColor Gray
Write-Host "后端目录: $ServerPath" -ForegroundColor Gray
Write-Host ""

# 步骤1: 创建config目录
Write-Host "步骤 1/5: 检查并创建config目录..." -ForegroundColor Yellow
if (-not (Test-Path $ConfigPath)) {
    New-Item -Path $ConfigPath -ItemType Directory -Force | Out-Null
    Write-Host "  ✓ config目录已创建" -ForegroundColor Green
} else {
    Write-Host "  ✓ config目录已存在" -ForegroundColor Green
}

# 步骤2: 设置server目录权限
Write-Host ""
Write-Host "步骤 2/5: 设置server目录权限..." -ForegroundColor Yellow
try {
    icacls $ServerPath /grant "IIS_IUSRS:(OI)(CI)F" /T /Q
    Write-Host "  ✓ server目录权限已设置" -ForegroundColor Green
} catch {
    Write-Host "  ❌ 设置权限失败: $_" -ForegroundColor Red
}

# 步骤3: 设置config目录权限
Write-Host ""
Write-Host "步骤 3/5: 设置config目录权限..." -ForegroundColor Yellow
try {
    icacls $ConfigPath /grant "IIS_IUSRS:(OI)(CI)F" /Q
    Write-Host "  ✓ config目录权限已设置" -ForegroundColor Green
} catch {
    Write-Host "  ❌ 设置权限失败: $_" -ForegroundColor Red
}

# 步骤4: 清理iisnode日志
Write-Host ""
Write-Host "步骤 4/5: 清理iisnode日志..." -ForegroundColor Yellow
$iisnodePath = Join-Path $ServerPath "iisnode"
if (Test-Path $iisnodePath) {
    Remove-Item (Join-Path $iisnodePath "*.log") -Force -ErrorAction SilentlyContinue
    Write-Host "  ✓ 日志已清理" -ForegroundColor Green
} else {
    Write-Host "  ℹ iisnode目录不存在（正常）" -ForegroundColor Gray
}

# 步骤5: 重启IIS站点和应用程序池
Write-Host ""
Write-Host "步骤 5/5: 重启IIS站点..." -ForegroundColor Yellow

try {
    Import-Module WebAdministration -ErrorAction Stop
    
    # 检查站点是否存在
    if (Test-Path "IIS:\Sites\$SiteName") {
        # 停止站点和应用程序池
        Stop-Website -Name $SiteName -ErrorAction SilentlyContinue
        Stop-WebAppPool -Name $PoolName -ErrorAction SilentlyContinue
        Write-Host "  · 站点已停止" -ForegroundColor Gray
        
        # 等待2秒
        Start-Sleep -Seconds 2
        
        # 启动应用程序池和站点
        Start-WebAppPool -Name $PoolName
        Start-Website -Name $SiteName
        Write-Host "  ✓ 站点已重启" -ForegroundColor Green
        
        # 等待站点启动
        Start-Sleep -Seconds 3
        
        # 测试健康检查
        Write-Host ""
        Write-Host "测试后端API..." -ForegroundColor Yellow
        try {
            $response = Invoke-WebRequest -Uri "http://localhost:8080/api/health" -UseBasicParsing -TimeoutSec 5
            $result = $response.Content | ConvertFrom-Json
            if ($result.success) {
                Write-Host "  ✓ 后端API正常运行" -ForegroundColor Green
                Write-Host "  · 响应: $($result.message)" -ForegroundColor Gray
            }
        } catch {
            Write-Host "  ⚠ 无法访问后端API" -ForegroundColor Yellow
            Write-Host "  · 错误: $_" -ForegroundColor Gray
            Write-Host ""
            Write-Host "  建议：" -ForegroundColor Yellow
            Write-Host "    1. 检查IIS站点是否正常运行" -ForegroundColor White
            Write-Host "    2. 查看 server\iisnode 目录下的日志文件" -ForegroundColor White
            Write-Host "    3. 确认iisnode模块已安装" -ForegroundColor White
        }
        
    } else {
        Write-Host "  ⚠ 站点 '$SiteName' 不存在" -ForegroundColor Yellow
        Write-Host "  · 请先运行部署脚本: .\deploy-iis-quick.ps1" -ForegroundColor Gray
    }
    
} catch {
    Write-Host "  ❌ 重启失败: $_" -ForegroundColor Red
    Write-Host "  · 可能原因：IIS未安装或WebAdministration模块不可用" -ForegroundColor Gray
}

Write-Host ""
Write-Host "=====================================" -ForegroundColor Cyan
Write-Host "修复完成！" -ForegroundColor Green
Write-Host "=====================================" -ForegroundColor Cyan
Write-Host ""

Write-Host "下一步测试：" -ForegroundColor Cyan
Write-Host "  1. 打开浏览器访问: http://localhost:8080" -ForegroundColor White
Write-Host "  2. 点击右上角的'设置'按钮" -ForegroundColor White
Write-Host "  3. 切换到'服务管理'标签页" -ForegroundColor White
Write-Host "  4. 点击'添加新服务'按钮进行测试" -ForegroundColor White
Write-Host ""

Write-Host "如果仍然失败，请查看：" -ForegroundColor Yellow
Write-Host "  - 故障排查文档: IIS故障排查指南.md" -ForegroundColor White
Write-Host "  - 日志位置: server\iisnode\*.log" -ForegroundColor White
Write-Host ""

Write-Host "当前权限设置：" -ForegroundColor Cyan
Write-Host "  Server目录权限:" -ForegroundColor Gray
icacls $ServerPath | Select-String "IIS_IUSRS"
Write-Host ""
Write-Host "  Config目录权限:" -ForegroundColor Gray
icacls $ConfigPath | Select-String "IIS_IUSRS"
Write-Host ""

pause
